package cn.sccl.dirms.monitor.controller;

import cn.sccl.common.model.PageResult;
import cn.sccl.common.database.DataBase;
import cn.sccl.common.model.QueryData;
import cn.sccl.common.web.BaseController;
import cn.sccl.dirms.monitor.model.Problem;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 告警
 * Created by liupan on 2017/3/6.
 */
@RestController
@RequestMapping(value = "/dirms/monitor/problem")
public class ProblemController extends BaseController {

    @Autowired
    private DataBase dataBase;

    /**
     * 获取问题数据
     */
    @RequestMapping(value = "/get", method = {RequestMethod.POST,RequestMethod.GET})
    public List<Problem> getProblem() {
        String sql = "select distinct  hs.hostid, hs.name hostname, REPLACE(tg.description,'{HOST.NAME}',hs.name) errorinfo, \n" +
                " tg.priority clevel, from_unixtime(tg.lastchange) time  \n" +
                "from   \n" +
                "   hosts            hs,  \n" +
                "   items            tt,  \n" +
                "   functions        ff,  \n" +
                "   triggers         tg  \n" +
                "where  \n" +
                "   hs.hostid = tt.hostid  \n" +
                " and tt.itemid = ff.itemid  \n" +
                " and tg.triggerid = ff.triggerid  \n" +
                " and tg.lastchange >0  \n" +
                " and tg.priority <=3 \n" +
                "order by from_unixtime(tg.lastchange) desc";
        return  this.dataBase.query4Model(sql, Problem.class);
    }

    /**
     * 根据level，获取问题数据
     * @param level 问题级别
     */
    @RequestMapping(value = "/getByLevel/{level}", method = {RequestMethod.POST,RequestMethod.GET})
    public List<Problem> getProblemByLevel(@PathVariable int level) {
        String sql = "select distinct  hs.hostid, hs.name hostname, REPLACE(tg.description,'{HOST.NAME}',hs.name) errorinfo, \n" +
                " tg.priority clevel, from_unixtime(tg.lastchange) time  \n" +
                "from   \n" +
                "   hosts            hs,  \n" +
                "   items            tt,  \n" +
                "   functions        ff,  \n" +
                "   triggers         tg  \n" +
                "where  \n" +
                "   hs.hostid = tt.hostid  \n" +
                " and tt.itemid = ff.itemid  \n" +
                " and tg.triggerid = ff.triggerid  \n" +
                " and tg.lastchange >0  \n" +
                " and tg.priority = ? \n" +
                "order by from_unixtime(tg.lastchange) desc";
        return  this.dataBase.query4Model(sql, Problem.class, new Object[]{level});
    }

    /**
     * 获取问题分页数据
     */
    @RequestMapping(value = "/pagequery", method = {RequestMethod.POST,RequestMethod.GET})
    public PageResult<Problem> getPageQueryProblem(HttpServletRequest request) {
        QueryData queryData = getQueryData(request);
        String sql = "SELECT DISTINCT\n" +
                        "hs.hostid,\n" +
                        "inf.ip hostip,\n" +
                        "hs. NAME hostname,\n" +
                        "REPLACE (tg.description,'{HOST.NAME}',hs. NAME) errorinfo,\n" +
                        "tg.priority clevel,\n" +
                        "from_unixtime(tg.lastchange) time\n" +
                    "FROM\n" +
                        "HOSTS hs,\n" +
                        "items tt,\n" +
                        "functions ff,\n" +
                        "TRIGGERS tg,\n" +
                        "interface inf\n" +
                    "WHERE\n" +
                        "hs.hostid = tt.hostid\n" +
                        "AND tt.itemid = ff.itemid\n" +
                        "AND tg.triggerid = ff.triggerid\n" +
                        "AND hs.hostid = inf.hostid\n" +
                        "AND tg.lastchange > 0\n" ;
        List<Object> params = new ArrayList<>();
        String keywords = MapUtils.getString(queryData,"keywords","");
        int alarmSelectModel = MapUtils.getInteger(queryData,"alarmSelectModel",-1);
        String timeRange = MapUtils.getString(queryData,"timeRange");
        String timeFormatter = MapUtils.getString(queryData,"timeFormatter","yyyy-MM-dd");
        Date startD = null;
        Date endD = null;
        if(!StringUtils.isEmpty(timeRange)){
            String start = timeRange.split(",")[0];
            String end = timeRange.split(",")[1];
            try {
                startD =  DateUtils.parseDate(start,timeFormatter);
            } catch (ParseException e) {

            }
            try {
                endD =  DateUtils.parseDate(end,timeFormatter);
            } catch (ParseException e) {

            }
        }
        if(startD != null && endD != null){
            sql += " and (tg.lastchange between ? and ? ) ";
            params.add(startD.getTime()/1000);
            Calendar c = Calendar.getInstance();
            c.setTime(endD);
            c.add(Calendar.HOUR_OF_DAY,24);
            c.add(Calendar.MILLISECOND,-1);
            params.add(c.getTime().getTime()/1000);
        }
        if(keywords != null && !"".equalsIgnoreCase(keywords)){
            sql += " and (inf.ip like ? \n or  hs. NAME like ? or  hs.hostid  like ?  or tg.description like ? ) ";
            params.add("%"+keywords+"%");
            params.add("%"+keywords+"%");
            params.add("%"+keywords+"%");
            params.add("%"+keywords+"%");
        }
        if(alarmSelectModel > -1){
            sql += " AND tg.priority = ? ";
            params.add(alarmSelectModel);
        }
        sql += " ORDER BY from_unixtime(tg.lastchange) DESC ";
        return this.dataBase.query4Model(sql,getPageIndex(request),getPageSize(request),Problem.class,params.toArray());
    }

    /**
     * 获取问题分页数据
     */
    @RequestMapping(value = "/all", method = {RequestMethod.POST,RequestMethod.GET})
    public List<Problem> getAllProblem(HttpServletRequest request) {
        QueryData queryData = getQueryData(request);
        String sql = "SELECT DISTINCT\n" +
                "hs.hostid,\n" +
                "inf.ip hostip,\n" +
                "hs. NAME hostname,\n" +
                "REPLACE (tg.description,'{HOST.NAME}',hs. NAME) errorinfo,\n" +
                "tg.priority clevel,\n" +
                "from_unixtime(tg.lastchange) time\n" +
                "FROM\n" +
                "HOSTS hs,\n" +
                "items tt,\n" +
                "functions ff,\n" +
                "TRIGGERS tg,\n" +
                "interface inf\n" +
                "WHERE\n" +
                "hs.hostid = tt.hostid\n" +
                "AND tt.itemid = ff.itemid\n" +
                "AND tg.triggerid = ff.triggerid\n" +
                "AND hs.hostid = inf.hostid\n" +
                "AND tg.lastchange > 0\n" ;
        List<Object> params = new ArrayList<>();
        String keywords = MapUtils.getString(queryData,"keywords","");
        int alarmSelectModel = MapUtils.getInteger(queryData,"alarmSelectModel",-1);
        String timeRange = MapUtils.getString(queryData,"timeRange");
        String timeFormatter = MapUtils.getString(queryData,"timeFormatter","yyyy-MM-dd");
        Date startD = null;
        Date endD = null;
        if(!StringUtils.isEmpty(timeRange)){
            String start = timeRange.split(",")[0];
            String end = timeRange.split(",")[1];
            try {
                startD =  DateUtils.parseDate(start,timeFormatter);
            } catch (ParseException e) {

            }
            try {
                endD =  DateUtils.parseDate(end,timeFormatter);
            } catch (ParseException e) {

            }
        }
        if(startD != null && endD != null){
            sql += " and (tg.lastchange between ? and ? ) ";
            params.add(startD.getTime()/1000);
            Calendar c = Calendar.getInstance();
            c.setTime(endD);
            c.add(Calendar.HOUR_OF_DAY,24);
            c.add(Calendar.MILLISECOND,-1);
            params.add(c.getTime().getTime()/1000);
        }
        if(keywords != null && !"".equalsIgnoreCase(keywords)){
            sql += " and (inf.ip like ? \n or  hs. NAME like ? or  hs.hostid  like ?  or tg.description like ? ) ";
            params.add("%"+keywords+"%");
            params.add("%"+keywords+"%");
            params.add("%"+keywords+"%");
            params.add("%"+keywords+"%");
        }
        if(alarmSelectModel > -1){
            sql += " AND tg.priority = ? ";
            params.add(alarmSelectModel);
        }
        sql += " ORDER BY from_unixtime(tg.lastchange) DESC ";
        return this.dataBase.query4Model(sql,Problem.class,params.toArray());
    }
}
